<%@ page import="com.example.dao.UserDao" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page import="java.util.Optional" %>
<%@ page import="java.security.MessageDigest" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 检查是否为POST请求
    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    request.setCharacterEncoding("UTF-8");
    
    try {
        int userId = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String realname = request.getParameter("realname");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        
        UserDao userDao = new UserDao();
        Optional<User> userOptional = userDao.getUserById(userId);
        if (!userOptional.isPresent()) {
            response.sendRedirect("user_list.jsp?error=用户不存在");
            return;
        }
        
        User user = userOptional.get();
        
        // 检查用户名是否被其他用户使用
        User existingUser = userDao.getUserByUsername(username);
        if (existingUser != null && existingUser.getId() != userId) {
            response.sendRedirect("user_edit.jsp?id=" + userId + "\u0026error=用户名已存在");
            return;
        }

        // 更新用户对象
        user.setUsername(username);
        user.setRealname(realname);
        user.setEmail(email);
        user.setPhone(phone);
        user.setAddress(address);
        
        // 只有当提供了新密码时才更新密码，并进行加密
        if (password != null && !password.trim().isEmpty()) {
            // 使用SHA-256加密密码
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                byte[] hash = md.digest(password.getBytes("UTF-8"));
                StringBuilder hexString = new StringBuilder();
                for (byte b : hash) {
                    hexString.append(String.format("%02x", b));
                }
                user.setPassword(hexString.toString());
            } catch (Exception e) {
                // 如果加密失败，记录错误并使用原始密码（这不是理想情况，但至少做了尝试）
                System.err.println("密码加密失败: " + e.getMessage());
                user.setPassword(password);
            }
        }

        // 更新数据库
        userDao.updateUser(user);

        // 重定向到用户列表页面
        response.sendRedirect("user_list.jsp?message=用户更新成功");
    } catch (Exception e) {
        response.sendRedirect("user_edit.jsp?id=" + request.getParameter("id") + "\u0026error=更新用户失败: " + e.getMessage());
    }
%>